from abc import ABC, abstractmethod
from typing import Dict, Any, Optional, List
from enum import Enum
import asyncio

class AIServiceType(str, Enum):
    """AI服务类型"""
    IMAGE_GENERATION = "image_generation"
    VIDEO_GENERATION = "video_generation"
    IMAGE_EDITING = "image_editing"
    FACE_SWAP = "face_swap"

class TaskStatus(str, Enum):
    """任务状态"""
    PENDING = "pending"
    PROCESSING = "processing"
    COMPLETED = "completed"
    FAILED = "failed"

class AIServiceProvider(str, Enum):
    """AI服务提供商"""
    OPENAI_DALLE = "openai_dalle"
    STABILITY_AI = "stability_ai"
    MIDJOURNEY = "midjourney"
    RUNWAY_ML = "runway_ml"      # Runway视频生成
    REPLICATE = "replicate"
    GOOGLE_VEO3 = "google_veo3"  # Google Veo 3
    JIMENG_AI = "jimeng_ai"      # 即梦AI视频生成

class GenerationRequest:
    """AI生成请求数据结构"""
    def __init__(
        self,
        prompt: str,
        service_type: AIServiceType,
        params: Optional[Dict[str, Any]] = None,
        user_id: int = None,
        job_id: int = None
    ):
        self.prompt = prompt
        self.service_type = service_type
        self.params = params or {}
        self.user_id = user_id
        self.job_id = job_id

class GenerationResponse:
    """AI生成响应数据结构"""
    def __init__(
        self,
        success: bool,
        result_url: Optional[str] = None,
        error_message: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None,
        cost: float = 0.0
    ):
        self.success = success
        self.result_url = result_url
        self.error_message = error_message
        self.metadata = metadata or {}
        self.cost = cost

class BaseAIService(ABC):
    """AI服务抽象基类"""
    
    def __init__(self, config: Dict[str, Any]):
        self.config = config
        self.provider = self.get_provider_name()
    
    @abstractmethod
    def get_provider_name(self) -> AIServiceProvider:
        """获取服务提供商名称"""
        pass
    
    @abstractmethod
    async def generate_image(self, request: GenerationRequest) -> GenerationResponse:
        """生成图片"""
        pass
    
    @abstractmethod
    async def generate_video(self, request: GenerationRequest) -> GenerationResponse:
        """生成视频"""
        pass
    
    @abstractmethod
    async def edit_image(self, request: GenerationRequest, image_url: str) -> GenerationResponse:
        """编辑图片"""
        pass
    
    @abstractmethod
    async def face_swap(self, request: GenerationRequest, source_url: str, target_url: str) -> GenerationResponse:
        """人脸替换"""
        pass
    
    @abstractmethod
    async def get_task_status(self, task_id: str) -> TaskStatus:
        """获取任务状态"""
        pass
    
    @abstractmethod
    def get_supported_services(self) -> List[AIServiceType]:
        """获取支持的服务类型"""
        pass
    
    def validate_request(self, request: GenerationRequest) -> bool:
        """验证请求参数"""
        if not request.prompt and request.service_type != AIServiceType.FACE_SWAP:
            return False
        return True
    
    def calculate_cost(self, request: GenerationRequest) -> float:
        """计算服务成本"""
        # 基础成本计算，子类可重写
        base_costs = {
            AIServiceType.IMAGE_GENERATION: 10,
            AIServiceType.VIDEO_GENERATION: 50,
            AIServiceType.IMAGE_EDITING: 15,
            AIServiceType.FACE_SWAP: 20
        }
        return base_costs.get(request.service_type, 10)